import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/flags_widget.dart';
import 'package:wch/helper/preferences_helper.dart';
import 'package:wch/model/flag_model.dart';
import 'package:wch/utils/color_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/text_utils.dart';
import 'package:wch/utils/time_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../model/acquisition_entity.dart';
import '../model/patient_label_list.dart';
import '../utils/overlay_utils.dart';
import 'alert_view.dart';

class RecycleDeviceAlert extends StatefulWidget {
  const RecycleDeviceAlert({super.key, required this.entry, required this.callback, required this.customRecycleMode});

  final OverlayEntry entry;

  final Function callback;

  final CustomRecycleMode customRecycleMode;

  @override
  State<RecycleDeviceAlert> createState() => _RecycleDeviceAlertState();
}

class _RecycleDeviceAlertState extends State<RecycleDeviceAlert> with WidgetsBindingObserver{
  String title = 'title';
  String deliveryDateLabel = 'deliveryDateLabel';
  String deliveryDateValue = 'deliveryDateValue';
  String deviceTypeLabel = 'deviceTypeLabel';
  String deviceTypeValue = 'deviceTypeValue';
  String deviceNameLabel = 'deviceNameLabel';
  String deviceNameValue = 'deviceNameValue';
  String deviceNumberLabel = 'deviceNumberLabel';
  String deviceNumberValue = 'deviceNumberValue';
  String pasterNameLabel = 'pasterNameLabel';
  String pasterNameValue = 'pasterNameValue';
  String collectingLabel = 'collectingLabel';///采集标签
  String collectingValue = 'collectingValue';
  String recyclePersonLabel = 'recyclePersonLabel';
  String recyclePersonValue = 'recyclePersonValue';
  String recycleDateLabel = 'recycleDateLabel';
  String recycleDateValue = 'recycleDateValue';
  String recycleDateIcon = 'recycleDateIcon';
  String remarkLabel = 'remarkLabel';
  String remarkValue = 'remarkValue';
  String tips = 'tips';
  String cancelBtn = 'cancelBtn';
  String okBtn = 'okBtn';

  TextEditingController remarkController = TextEditingController();

  bool isShowRemarkHint = true;

  ///顶部距离，在弹出/关闭键盘时，会修改顶部距离
  double topMargin = 128.h;
  double bottomMargin = 59.h;
  ///上次键盘弹出关闭状态,1开启
  int lastKeyboardStatus = 0;

  ///时间弹窗 overlay
  OverlayEntry? timeOverlayEntry;
  
  List<Widget> flagsWidgetList = [];

  double flagsWidgetHeight = 0;

  ///备注控制器
  TextEditingController _doctorController = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);

    _doctorController.text = PreferencesHelper.getPerson() ?? '';

    remarkController.addListener(() {
      setState(() {
        isShowRemarkHint = remarkController.text.isEmpty;
      });
    });

    List<FlagModel> flags = [];
    List<AcquisitionAcquisitionLabelList>? labels = widget.customRecycleMode.label;
    if (labels == null || labels.isEmpty) return;

    for(int i = 0; i < widget.customRecycleMode.label!.length; i ++) {
      AcquisitionAcquisitionLabelList label = widget.customRecycleMode.label![i];
      FlagModel model = FlagModel(label.name!, false);
      Color color = ColorUtils.getColorFromHex(label.colour!);
      model.textColor = color;
      model.backgroundColor = color.withOpacity(0.2);
      flags.add(model);
    }
    // flagsWidgetList = FlagsWidget.getFlagsWidget(['术前两天术前两天', '术前3天', '病房', '病房', '病房', '术前两天', '术前3天', '病房', '11122233', '11122233', '11122233'], ScreenUtil().screenWidth-180.w, 50.h, 10, (widgetHeight){
    flagsWidgetList = FlagsWidget.getFlagsWidget2(flags, ScreenUtil().screenWidth-180.w, 50.h, 10, (widgetHeight){
      flagsWidgetHeight = widgetHeight;
    });
  }
  @override
  void dispose() {
    // 销毁
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  // 监听
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if(mounted){
        if(MediaQuery.of(context).viewInsets.bottom==0){
          // 关闭键盘
          // LogUtils.log('关闭键盘');
          if (lastKeyboardStatus == 1) {
            lastKeyboardStatus = 0;
            setState(() {
              topMargin = 128.h;
              bottomMargin = 59.h;
            });
          }
        }else{
          // 显示键盘
          // LogUtils.log('打开键盘');
          if (lastKeyboardStatus == 0) {
            lastKeyboardStatus = 1;
            setState(() {
              topMargin = 28.h;
              bottomMargin = 159.h;
            });
          }
        }
      }
    });
  }

  double getBottomMargin() {
    double margin = bottomMargin;
    if (flagsWidgetList.isEmpty) {
      margin += 50.h;
    }
    if (widget.customRecycleMode.deviceName == null) {
      margin += 20.h;
    }
    // if (widget.customRecycleMode.pasterName == null) {
    //   margin += 20.h;
    // }
    return margin;
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: Container(
        color: alphaColor,
        child: ConstraintLayout(
          children: [
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(15.w)),
                color: Colors.white
              )
            ).applyConstraint(
                left: parent.left.margin(27.5.w),
                right: parent.right.margin(27.5.w),
                top: parent.top.margin(topMargin),
                bottom: parent.bottom.margin(getBottomMargin()),
                width: matchConstraint,
                height: matchConstraint,
            ),
            const Text('回收设备', style: TextStyle(fontSize: 16, color: Color(0xFF262626), fontWeight: FontWeight.w600),).applyConstraint(
              centerHorizontalTo: rId(0),
              top: rId(0).top.margin(22.5.h),
              id: ConstraintId(title),
            ),
            _getLabelWidget('分配日期：').applyConstraint(
              left: rId(0).left.margin(15.w),
              top: cId(title).bottom.margin(20.h),
              id: ConstraintId(deliveryDateLabel)
            ),
            _getValueWidget(widget.customRecycleMode.deliveryDate ?? '').applyConstraint(
              left: cId(deliveryDateLabel).right.margin(7.5.w),
              top: cId(deliveryDateLabel).top,
              id: ConstraintId(deliveryDateValue)
            ),
            _getLabelWidget('设备类型：').applyConstraint(
                left: rId(0).left.margin(15.w),
                top: cId(deliveryDateLabel).bottom.margin(20.h),
                id: ConstraintId(deviceTypeLabel)
            ),
            _getValueWidget('脑电一体机').applyConstraint(
                left: cId(deviceTypeLabel).right.margin(7.5.w),
                top: cId(deviceTypeLabel).top,
                id: ConstraintId(deviceTypeValue)
            ),
            _getLabelWidget('设备名称：').applyConstraint(
                left: rId(0).left.margin(15.w),
                top: cId(deviceTypeLabel).bottom.margin(20.h),
                id: ConstraintId(deviceNameLabel)
            ),
            _getValueWidget(widget.customRecycleMode.deviceNumber ?? '').applyConstraint(
                left: cId(deviceNameLabel).right.margin(7.5.w),
                top: cId(deviceNameLabel).top,
                id: ConstraintId(deviceNameValue)
            ),
            _getLabelWidget('设备编号：').applyConstraint(
                left: rId(0).left.margin(15.w),
                top: cId(deviceNameLabel).bottom.margin(20.h),
                id: ConstraintId(deviceNumberLabel),
                height: widget.customRecycleMode.deviceName == null ? 0 : 20.h
            ),
            _getValueWidget(widget.customRecycleMode.deviceName ?? '').applyConstraint(
                left: cId(deviceNumberLabel).right.margin(7.5.w),
                top: cId(deviceNumberLabel).top,
                id: ConstraintId(deviceNumberValue),
                height: widget.customRecycleMode.deviceName == null ? 0 : 20.h
            ),
            _getLabelWidget('脑贴名称：').applyConstraint(
                left: rId(0).left.margin(15.w),
                top: cId(deviceNumberLabel).bottom.margin(20.h),
                id: ConstraintId(pasterNameLabel),
            ),
            _getValueWidget(widget.customRecycleMode.pasterName ?? '').applyConstraint(
                left: cId(pasterNameLabel).right.margin(7.5.w),
                top: cId(pasterNameLabel).top,
                id: ConstraintId(pasterNameValue),
            ),
            _getLabelWidget('采集标签：').applyConstraint(
                left: rId(0).left.margin(15.w),
                top: cId(pasterNameLabel).bottom.margin(20.h),
                id: ConstraintId(collectingLabel),
              height: flagsWidgetList.isEmpty ? 0 : 20.h
            ),
            Container(
              width: ScreenUtil().screenWidth-180.w,
              height: flagsWidgetList.isEmpty ? 0 : (flagsWidgetHeight > 50 ? 50 : flagsWidgetHeight),
              child: Stack(
                children: flagsWidgetList,
              ),
            ).applyConstraint(
              left: cId(pasterNameValue).left,
              right: rId(0).right.margin(30.w),
              top: cId(collectingLabel).top,
                height: flagsWidgetHeight > 50 ? 50 : flagsWidgetHeight,
              width: matchConstraint
            ),
      
            LineWidget(width: ScreenUtil().screenWidth-55.w, height: 0.5).applyConstraint(
              left: rId(0).left,
              right: rId(0).right,
              top: cId(collectingLabel).bottom.margin(35.h),
              height: 0.5.w,
              id: cId('sepLine'),
            ),
            _getLabelWidget('回收人：').applyConstraint(
              top: cId('sepLine').bottom.margin(20.h),
              right: cId(collectingLabel).right,
              id: ConstraintId(recyclePersonLabel)
            ),
            _getSingleLineWidget('请输入医生', PreferencesHelper.getPerson() ?? '').applyConstraint(
              left: cId(recyclePersonLabel).right.margin(7.5.w),
              right: rId(0).right.margin(15.w),
              height: 30.h,
              centerVerticalTo: cId(recyclePersonLabel),
              width: matchConstraint
            ),
            _getLabelWidget('回收日期：').applyConstraint(
              top: cId(recyclePersonLabel).bottom.margin(20.h),
              right: cId(recyclePersonLabel).right,
              id: ConstraintId(recycleDateLabel)
            ),
            GestureDetector(
              onTap: (){
                timeOverlayEntry = OverlayEntry(builder: (ctx){
                  return SelectTimePicker2(title: '设备回收时间', date: TimeUtils.getCurDate('-'), callback: (time){
                    setState(() {
                      widget.customRecycleMode.recycleDate = time;
                    });
                  }, overlay: timeOverlayEntry!, time: TimeUtils.getCurHourMinute(),);
                });
                Overlay.of(context).insert(timeOverlayEntry!);
              },
              child: _getSingleLineIconWidget('请选择日期', widget.customRecycleMode.recycleDate ?? TimeUtils.getCurTime('-')),
            ).applyConstraint(
                left: cId(recycleDateLabel).right.margin(7.5.w),
                right: rId(0).right.margin(15.w),
                height: 30.h,
                centerVerticalTo: cId(recycleDateLabel),
                width: matchConstraint
            ),
            _getLabelWidget('备注：').applyConstraint(
              top: cId(recycleDateLabel).bottom.margin(20.h),
              right: cId(recycleDateLabel).right,
              id: ConstraintId(remarkLabel)
            ),
            _getMulLineWidget('content', remarkController).applyConstraint(
              top: cId(recycleDateLabel).bottom.margin(20.h),
              left: cId(remarkLabel).right.margin(7.5.w),
              right: rId(0).right.margin(15.w),
              width: matchConstraint,
              height: 100.h,
              id: ConstraintId(remarkValue),
            ),
            ///备注输入的 hint
            Offstage(
              offstage: !isShowRemarkHint,
              child: F13TitleText(
                '请输入备注',
                color: F2TextColor,
              ),
            ).applyConstraint(
              left: cId(remarkValue).left.margin(12.w),
              top: cId(remarkValue).top.margin(5.w),
            ),
            F10TitleText('注：一体机需要在有Wi-Fi 的情况下，才可完成回收', color: Color(0xFFF78554)).applyConstraint(
              left: cId(recycleDateLabel).left,
              right: rId(0).right,
              top: cId(remarkValue).bottom.margin(24.h),
              width: matchConstraint,
              id: ConstraintId(tips)
            ),
            LineWidget(width: ScreenUtil().screenWidth-60.w, height: 0.5).applyConstraint(
              left: rId(0).left,
              right: rId(0).right,
              height: 0.5,
              top: cId(tips).bottom.margin(24.h),
              width: matchConstraint,
                id: ConstraintId('horline2')
            ),
            LineWidget(width: 0.5, height: 55.h).applyConstraint(
              centerHorizontalTo:parent,
              width: 0.5,
              top: cId(tips).bottom.margin(24.h),
              bottom: rId(0).bottom,
              height: matchConstraint,
              id: ConstraintId('verline')
            ),
            GestureDetector(
              onTap: (){
                widget.callback(0, '', '');
                widget.entry!.remove();
              },
              child: F16TitleText('取消', color: Color(0xFF262626))
            ).applyConstraint(
              left: rId(0).left,
              right: cId('verline').left,
              top: cId('horline2').bottom,
              bottom: cId('verline').bottom,
            ),
            GestureDetector(
              onTap: (){
                if (!TextUtils.isNotNull(_doctorController.text)) {
                  ToastUtils.showToast(msg: '请填写回收人');
                  return;
                }
                if (!TextUtils.isNotNull(widget.customRecycleMode.recycleDate)) {
                  ToastUtils.showToast(msg: '请选择回收时间');
                  return;
                }
                widget.callback(1, widget.customRecycleMode.recycleDate, remarkController.text);
                widget.entry!.remove();
              },
              child: F16TitleText('确定', color: themeColor)
            ).applyConstraint(
              right: rId(0).right,
              left: cId('verline').right,
              top: cId('horline2').bottom,
              bottom: cId('verline').bottom,
            ),
          ],
        ),
      ),
    );
  }

  Widget _getLabelWidget(String label) {
    // return F13TitleText(label, color: const Color(0xFF262626));
    return Text(label, style: TextStyle(color: Color(0xFF262626), fontSize: 13, fontWeight: FontWeight.w600),);
  }
  Widget _getValueWidget(String label) {
    return F13TitleText(label, color: const Color(0xFF515151));
  }
  ///单行输入
  Widget _getSingleLineWidget(String hint, String content) {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFFF3F5FA),
        borderRadius: BorderRadius.all(Radius.circular(5.h)),
      ),
      padding: EdgeInsets.symmetric(horizontal: 5.w),
      child: CupertinoTextField(
        // controller: controller,
        placeholder: hint,
        controller: hint == '请输入医生' ? _doctorController : null,
        placeholderStyle: TextStyle(
          fontSize: 13.w,
          color:F2TextColor,
        ),
        style: TextStyle(
          fontSize: 14,
          color: F1TextColor
        ),
        decoration:
        const BoxDecoration(color: Colors.transparent),
      )
    );
  }
  ///单行选择 + icon
  Widget _getSingleLineIconWidget(String hint, String content) {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFFF3F5FA),
        borderRadius: BorderRadius.all(Radius.circular(5.h)),
      ),
      padding: EdgeInsets.all(5.w),
      child: Row(
        children: [
          HorPadding(7.w),
          Expanded(child: F13TitleText(content.isNotEmpty ? content : hint, color: F2TextColor,)),
          HorPadding(5.w),
          Image.asset(dateIcon, width: 13.5.w, height: 15.h,),
          HorPadding(5.w),
        ],
      )
    );
  }
  ///多行输入
  Widget _getMulLineWidget(String content, TextEditingController controller) {
    return Container(
        decoration: BoxDecoration(
          color: Color(0xFFF3F5FA),
          borderRadius: BorderRadius.all(Radius.circular(5.h)),
        ),
        padding: EdgeInsets.symmetric(horizontal: 5.w),
        child: CupertinoTextField(
          maxLines: 5,
          maxLength: 50,
          controller: controller,
          style: TextStyle(
            fontSize: 13.w,
            color:F2TextColor,
          ),
          decoration:
          const BoxDecoration(color: Colors.transparent),
        )
    );
  }
}

///自定义回收模型
class CustomRecycleMode {
  final String? deliveryDate;
  final String? deviceId;
  final String? deviceName;
  final String? deviceNumber;
  final String? pasterName;
  final List<AcquisitionAcquisitionLabelList>? label;
  final String? doctor;///回收人
  String? recycleDate;
  final String? remark;

  CustomRecycleMode(this.deliveryDate, this.deviceId, this.deviceName,
      this.pasterName, this.label, this.doctor, this.recycleDate, this.remark, this.deviceNumber);
}
